package com.sanji.sjmallmodule.order;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallutils.Tools;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sanji.sjmallapp.MallApplication.myShare;

/**
 * 我的订单
 * Created by zsf on 17-1-12.
 */

public class MyOrderActivity extends FragmentActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, NoHttpListener {
    @BindView(R.id.common_back_img)
    ImageView mCommonBackImg;
    @BindView(R.id.common_left_tv)
    TextView mCommonLeftTv;
    @BindView(R.id.common_right_img)
    ImageView mCommonRightImg;
    @BindView(R.id.my_order_all_btn)
    RadioButton mMyOrderAllBtn;
    @BindView(R.id.my_order_unpaid_btn)
    RadioButton mMyOrderUnpaidBtn;
    @BindView(R.id.my_order_unshipped_btn)
    RadioButton mMyOrderUnshippedBtn;
    @BindView(R.id.my_order_account_paid_btn)
    RadioButton mMyOrderAccountPaidBtn;
    @BindView(R.id.my_order_title_group)
    RadioGroup mMyOrderTitleGroup;
    @BindView(R.id.my_order_point_line)
    ImageView mMyOrderPointLine;
    @BindView(R.id.my_order_viewpager)
    ViewPager mMyOrderViewpager;
    Bundle bundle = new Bundle();

    private List<MyOrderFragment> fragmentList;

    private int offset = 0;//动画图片偏移量
    private int currIndex = 0;//当前页卡编号
    private int bmpW;//动画图片宽度
    private SharePreferenceUtil myShare;
    private Request<JSONObject> request;

    String orderNumberUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order);
        ButterKnife.bind(this);
        currIndex = getIntent().getIntExtra("pageIndex", 0);
        initViews();
        initImageView();
        initViewPager();
        requestNumber();
    }

    private void initViews() {
        mCommonBackImg.setVisibility(View.VISIBLE);
        mCommonBackImg.setOnClickListener(this);
        mCommonLeftTv.setVisibility(View.VISIBLE);
        mCommonLeftTv.setText(getResources().getString(R.string.my_order_title));
        mMyOrderTitleGroup.setOnCheckedChangeListener(this);
        myShare = MallApplication.myShare;
    }

    private void initImageView() {
        //图片宽度
        bmpW = BitmapFactory.decodeResource(getResources(), R.mipmap.line_tab_bom).getWidth();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;//获取屏幕宽度
        offset = (screenW / 4 - bmpW) / 2;//计算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        mMyOrderPointLine.setImageMatrix(matrix);
    }

    private void initViewPager() {
        fragmentList = new ArrayList<>();
        MyOrderFragment allOrder = new MyOrderFragment();
        Bundle allOrderBundle = new Bundle();
        allOrderBundle.putInt("pages", 0);
        allOrder.setArguments(allOrderBundle);
        MyOrderFragment unPaidOrder = new MyOrderFragment();
        Bundle unPaidOrderBundle = new Bundle();
        unPaidOrderBundle.putInt("pages", 1);
        unPaidOrder.setArguments(unPaidOrderBundle);
        MyOrderFragment unShipedOrder = new MyOrderFragment();
        Bundle unShipedOrderBundle = new Bundle();
        unShipedOrderBundle.putInt("pages", 2);
        unShipedOrder.setArguments(unShipedOrderBundle);
        MyOrderFragment paidOrder = new MyOrderFragment();
        Bundle paidOrderBundle = new Bundle();
        paidOrderBundle.putInt("pages", 3);
        paidOrder.setArguments(paidOrderBundle);
        fragmentList.add(allOrder);
        fragmentList.add(unPaidOrder);
        fragmentList.add(unShipedOrder);
        fragmentList.add(paidOrder);
        switch (currIndex) {
            case 0:
                allOrderBundle.putInt("pages", 0);
                allOrder.setArguments(allOrderBundle);
                break;
            case 1:
                unPaidOrderBundle.putInt("pages", 1);
                unPaidOrder.setArguments(unPaidOrderBundle);
                break;
            case 2:
                unShipedOrderBundle.putInt("pages", 2);
                unShipedOrder.setArguments(unShipedOrderBundle);
                break;
            case 3:
                paidOrderBundle.putInt("pages", 3);
                paidOrder.setArguments(paidOrderBundle);
                break;
        }
        mMyOrderViewpager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList));
        mMyOrderViewpager.setOnPageChangeListener(new MyOnPageChangeListener());
        mMyOrderViewpager.setCurrentItem(currIndex);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back_img:
                finish();
                break;
            case R.id.common_right_img:

                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.my_order_all_btn:
                mMyOrderViewpager.setCurrentItem(0);
                break;
            case R.id.my_order_unpaid_btn:
                mMyOrderViewpager.setCurrentItem(1);
                break;
            case R.id.my_order_unshipped_btn:
                mMyOrderViewpager.setCurrentItem(2);
                break;
            case R.id.my_order_account_paid_btn:
                mMyOrderViewpager.setCurrentItem(3);
                break;
        }
    }

    @Override
    public void onSuccessed(int what, Response response) {
        JSONObject json = (JSONObject) response.get();
        if (what == orderNumberUrl.hashCode()) {
            String status = json.optString(ConfigConts.STATUS_STRING);
            if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                JSONObject object = json.optJSONObject("result");
                int paidNumber = object.optInt("paidNum");
                int unPaidNumber = object.optInt("obligationNum");
                int unShipNumber = object.optInt("staySendNum");

                mMyOrderUnpaidBtn.setText(String.format(getResources().getString(R.string.order_paying),unPaidNumber));
                mMyOrderUnshippedBtn.setText(String.format(getResources().getString(R.string.order_shipping),unShipNumber));
                mMyOrderAccountPaidBtn.setText(String.format(getResources().getString(R.string.order_payed),paidNumber));
                if (unPaidNumber == 0 || unShipNumber == 0) {
                    setResult(RESULT_OK);
                }
            } else if (status.equals(ConfigConts.STATUS_ERROR)) {
                String errorMsg = json.optString(ConfigConts.ERRORMSG);
                Tools.toastTools(this, errorMsg);
            }
        }

    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(this, getResources().getString(R.string.request_time_out));
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        private int one = offset * 2 + bmpW;//两个相邻页面的偏移量

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Animation animation = new TranslateAnimation(currIndex * one, position * one, 0, 0);//平移动画
            currIndex = position;
            animation.setFillAfter(true);//动画终止时停留在最后一帧，不然会回到没有执行前的状态
            animation.setDuration(200);//动画持续时间0.2秒
            mMyOrderPointLine.startAnimation(animation);//是用ImageView来显示动画的
//            int i = currIndex + 1;
//            Toast.makeText(MyOrderActivity.this, "您选择了第"+i+"个页卡", Toast.LENGTH_SHORT).show();
            switch (position) {
                case 0:
                    mMyOrderAllBtn.setChecked(true);
                    break;
                case 1:
                    mMyOrderUnpaidBtn.setChecked(true);
                    break;
                case 2:
                    mMyOrderUnshippedBtn.setChecked(true);
                    break;
                case 3:
                    mMyOrderAccountPaidBtn.setChecked(true);
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != request) {
            request.cancel();
        }
    }

    /**
     * 网络请求订单数量
     */
    public void requestNumber() {
        String userId = myShare.getString(ConfigConts.USER_ID, null);
        orderNumberUrl = ConfigAPI.MY_ORDER_NUMBER_URL + userId;
        request = NoHttp.createJsonObjectRequest(orderNumberUrl, RequestMethod.GET);
        request.setCancelSign(orderNumberUrl.hashCode());
        NoHttpCallBack.getInstance().add(this, orderNumberUrl.hashCode(), request, this, true, true);
    }
}
